package com.elong.android.specialhouse.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.HouseInfoRequestParam;
import com.elong.android.specialhouse.entity.HouseItemList;
import com.elong.android.specialhouse.request.CollectionReq;
import com.elong.android.specialhouse.request.GetHouseCollectionReq;
import com.elong.android.specialhouse.ui.SuperListView;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的收藏
 * 
 * @author lin.chai
 * @date 2015年9月17日 上午11:29:05
 */
public class MyCollectionActivity extends BaseVolleyActivity<IResponse<?>> implements  OnItemClickListener, ViewTreeObserver.OnPreDrawListener{
    private static final String PAGE_NAME = "youfangCollectionPage";
    private static final String TAG = "MyCollectionActivity";
    private ImageView ivMessage;
    private LinearLayout llEmptyHint;
    private Button btnLogin;
    private SuperListView lvCollection;
    private PowerAdapter<HouseItemList> mCollectionListAdapter;
    private List<HouseItemList> mCollectionListEntities = new ArrayList<HouseItemList>();

    private boolean isLogin;
    private long mUserId;
    private int mTotalHouseCount = 0;
    private int mCurrentPageIndex = 1;
    private GetHouseCollectionReq mGetHouseCollectionReq;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventReportTools.sendPageOpenEvent(PAGE_NAME);
    }

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_my_collection);
        setHeader(R.string.my_collection);
        getWindow().getDecorView().getViewTreeObserver()
                .addOnPreDrawListener(this);
        ivMessage = (ImageView) findViewById(R.id.common_message);
        ivMessage.setVisibility(View.VISIBLE);
        llEmptyHint = (LinearLayout) findViewById(R.id.ll_empty_hint);
        btnLogin = (Button) findViewById(R.id.btn_login);    
        lvCollection = (SuperListView) findViewById(R.id.lv_collection);
        findViewById(R.id.common_head_back).setVisibility(View.GONE);

        isLogin = Account.getInstance().isLogin();
        refreshUI();
        setupListView();
        setListener();
    }
    @Override
    protected void onResume() {
    	super.onResume();
    }

    /**
     * 网络请求获取收藏列表
     */
    private void requestCollectionHouseList(boolean isShowDialog) {
        mGetHouseCollectionReq = new GetHouseCollectionReq();
        mGetHouseCollectionReq.UserId = mUserId;
        mGetHouseCollectionReq.PageIndex = mCurrentPageIndex;
        mGetHouseCollectionReq.PageSize = 0;//不分页
        requestHttp(mGetHouseCollectionReq, ApartmentAPI.getCollectionInfo, StringResponse.class, isShowDialog);
    }


    private void setListener() {
    	lvCollection.setOnItemClickListener(this);
        lvCollection.setOnRefreshListener(new SuperListView.OnPullDownRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPageIndex = 1;
                requestCollectionHouseList(false);
            }
        });
        lvCollection.setLastPage();//取消分页加载
//        lvCollection.setOnLoadMoreListener(new SuperListView.OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                if (mCollectionListEntities.size() < mTotalHouseCount) {
//                    requestCollectionHouseList(false);
//                } else {
//                    lvCollection.onLoadMoreComplete();
//                }
//
//            }
//        });
    	btnLogin.setOnClickListener(this);
    }

    /**
     * 填充列表页
     */
    private void setupListView() {
        mCollectionListAdapter = new PowerAdapter<HouseItemList>(MyCollectionActivity.this, R.layout.item_home_list, mCollectionListEntities) {
            @Override
            protected void convert(final BaseViewHolder holder, final HouseItemList item) {
                setupApartmentTextInfo(holder, item);
                holder.setImageUrl(R.id.iv_landlord_pic_url, item.LandlordPicUrl,R.drawable.default_user_photo);
                holder.setImageUrl(R.id.iv_apartment_image, item.RoomPicUrl);
                holder.setImageResource(R.id.iv_collection, R.drawable.icon_collect_selected);
//                holder.setImageResource(R.id.iv_collection, item.IsCollected ? R.drawable.icon_collect_selected : R.drawable.icon_collect_unselected);
                holder.setOnClickListener(R.id.iv_collection, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    	CollectionReq req = new CollectionReq() ;
                    	req.UserId = Account.getInstance().getUserId() ;
                        req.HouseId = item.HouseId ;
                        req.Index = holder.getPosition() ;
                        //删除收藏
                        requestHttp(req,ApartmentAPI.deleteCollectionInfo,StringResponse.class,true) ;
                        
                    }
                });
            }
        };
        lvCollection.setAdapter(mCollectionListAdapter);
    }

    /**
     * 设置公寓价格文字
     */
    private void setupApartmentTextInfo(BaseViewHolder holder, final HouseItemList item) {
        //设置公寓名
        holder.setText(R.id.tv_apartment_name, item.HouseName);
        //设置价格信息
        String price = StringUtils.toRoundInt(item.DailyPrice + "");
        SpannableString priceSpan = new SpannableString("￥" + price + "/晚");
        int priceTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 22, this.getResources().getDisplayMetrics());
        priceSpan.setSpan(new AbsoluteSizeSpan(priceTextSize, false), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        priceSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_yellow)), 1, priceSpan.length() - 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        holder.setText(R.id.tv_daily_price, priceSpan);
        //设置公寓地址 有商圈显示商圈，无则显示行政区
        holder.setText(R.id.tv_address, !TextUtils.isEmpty(item.BusinessAreaName) ? item.BusinessAreaName : item.DistrictName);
        //设置出租类型
        switch (item.RentalType) {
            case AppConstants.SPACE_TYPE_WHOLE_HOUSE:        // 整租 则显示户型
                holder.setText(R.id.tv_rental_type, item.RoomAndLobby);
                break;
            case AppConstants.SPACE_TYPE_ONE_ROOM:         // 单间
                holder.setText(R.id.tv_rental_type, getString(R.string.oneroom));
                break;
            case AppConstants.SPACE_TYPE_BED_ONLY:         // 床位
                holder.setText(R.id.tv_rental_type, getString(R.string.bedonly));
                break;
            default:
                break;
        }

    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        // 处理网络返回结果
        String content = ((StringResponse) t).getContent();
        JSONObject result = JSONObject.parseObject(content);
        boolean isHandlerError = handleIsError(request, result);   //是否已经处理过IsError信息
        if (((ApartmentAPI) request.getRequestOption().getHusky()) == ApartmentAPI.getCollectionInfo) {
        	lvCollection.onLoadMoreComplete();
            lvCollection.onRefreshComplete();
        }
        if (!isHandlerError) {
            switch ((ApartmentAPI) request.getRequestOption().getHusky()) {
                case getCollectionInfo:
//                    showListDataByPage(result);
                    showAllListData(result);
                    break;
                case deleteCollectionInfo:
                    //删除数据刷新
                    Toast.makeText(this, R.string.cancel_collection_success, Toast.LENGTH_SHORT).show();
                    if (result.containsKey(JSONConstants.ATTR_INDEX)) {
                        int index = result.getIntValue(JSONConstants.ATTR_INDEX);
                        mCollectionListAdapter.remove(index);
                        mCollectionListEntities.remove(index);
                        mTotalHouseCount--;
                        //没有分页加载，全部取消收藏后提示没有收藏，不用mTotalHouseCount做判断
                        if(mCollectionListEntities.isEmpty()){
                            llEmptyHint.setVisibility(View.VISIBLE);
                            btnLogin.setVisibility(View.GONE);
                        }
//                        if(mCollectionListEntities.isEmpty()){
//                            if(mTotalHouseCount == 0){
//                                //页面显示数据清空且收藏总数为0，提示没有收藏
//                                llEmptyHint.setVisibility(View.VISIBLE);
//                                btnLogin.setVisibility(View.GONE);
//                            }else{
//                                //页面显示数据清空但收藏总数不为0，重新请求数据
//                                refreshUI();
//                            }
//                        }
                    }
                    break;
                default:
                    break;
            }
        } else {
            if (((ApartmentAPI) request.getRequestOption().getHusky()) == ApartmentAPI.deleteCollectionInfo) {
                Toast.makeText(this,R.string.cancel_collection_failed,Toast.LENGTH_SHORT).show();
            }
        }

    }
    /**
     * 全部数据显示
     *
     * */
    private void showAllListData(JSONObject result) {
        mTotalHouseCount = result.containsKey(JSONConstants.ATTR_HOUSE_TOTAL) ? result.getIntValue(JSONConstants.ATTR_HOUSE_TOTAL) : 0;
        List<HouseItemList> houseList = JSONArray.parseArray(result.getString(JSONConstants.ATTR_HOUSE_ITEMS), HouseItemList.class);
        if (houseList != null && houseList.size() > 0) {
            llEmptyHint.setVisibility(View.GONE);
            mCollectionListAdapter.replaceAll(houseList);
            mCollectionListEntities.clear();
            mCollectionListEntities.addAll(houseList);
        }else {
            mCollectionListAdapter.clear();
            mCollectionListEntities.clear();
            llEmptyHint.setVisibility(View.VISIBLE);
            btnLogin.setVisibility(View.GONE);
        }
    }
    /**
     * 分页加载数据显示
     *
     * */
    private void showListDataByPage(JSONObject result) {
        mTotalHouseCount = result.containsKey(JSONConstants.ATTR_HOUSE_TOTAL) ? result.getIntValue(JSONConstants.ATTR_HOUSE_TOTAL) : 0;
        if (mTotalHouseCount > 0) {
            llEmptyHint.setVisibility(View.GONE);
            List<HouseItemList> houseList = JSONArray.parseArray(result.getString(JSONConstants.ATTR_HOUSE_ITEMS), HouseItemList.class);
            if (houseList != null && houseList.size() > 0) {
                if(mCurrentPageIndex > 1){
                    //分页加载
                    mCollectionListAdapter.addAll(houseList);
                    mCollectionListEntities.addAll(houseList);
                }else{
                    //刷新列表
                    mCollectionListAdapter.replaceAll(houseList);
                    mCollectionListEntities.clear();
                    mCollectionListEntities.addAll(houseList);
                }
            }
        } else if(mCurrentPageIndex == 1){
            mCollectionListAdapter.clear();
            mCollectionListEntities.clear();
            llEmptyHint.setVisibility(View.VISIBLE);
            btnLogin.setVisibility(View.GONE);
        }
        mCurrentPageIndex++;//返回成功索引值加1
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 跳转到公寓详情页
        if(position>0){
            Intent intent = new Intent(this, ApartmentDetailsActivity.class);
            HouseInfoRequestParam param = new HouseInfoRequestParam();
            param.HouseItemList = mCollectionListAdapter.getItem(position - 1);
            param.HouseItemList.IsCollected = true;
            intent.putExtra("ApartmentInfoRequestParam", param);
            startActivity(intent);
        }
    }
    @Override
    public void onClick(View v) {
   	    super.onClick(v);
   	    switch(v.getId()){
   	        case R.id.common_message:
   	        	break;
   	        case R.id.btn_login:
   	    	    startActivity(new Intent(MyCollectionActivity.this, LoginActivity.class));
   		        break;
   	        default:
   		        break;
   	    }
    }
    @Override
    public boolean onPreDraw() {
        if(isLogin != Account.getInstance().isLogin()){
            isLogin = Account.getInstance().isLogin();
            refreshUI();
        }
        return true ;
    }
    public void refreshUI(){
        if(mCollectionListAdapter != null){
            mCollectionListEntities.clear();
            mCollectionListAdapter.clear();
            mCurrentPageIndex = 1;
        }
        if(Account.getInstance().isLogin()){
            mUserId = Long.parseLong(Account.getInstance().getUserId());
            requestCollectionHouseList(true);
            lvCollection.setVisibility(View.VISIBLE);
            llEmptyHint.setVisibility(View.GONE);
        }else{
            lvCollection.setVisibility(View.GONE);
            llEmptyHint.setVisibility(View.VISIBLE);
            btnLogin.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_HOME ;
    }
}